package gappengko;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.tanesha.recaptcha.ReCaptchaImpl;
import net.tanesha.recaptcha.ReCaptchaResponse;

/** very simple adapter from HttpServletRequest to ReCaptchaImpl*/
public class RecaptchaUtils {

  /** the private Recaptcha key */
  public static boolean _isEnabled = "yes".equals(System.getProperty("gappengko.recaptcha"));

  /** the private Recaptcha key */
  public static final String RECAPTCHA_PRIVATE_KEY = System.getProperty("gappengko.RECAPTCHA_PRIVATE_KEY");

	public static final String RECAPTCHA_RESPONSE_FIELD = "recaptcha_response_field";
	public static final String RECAPTCHA_CHALLENGE_FIELD = "recaptcha_challenge_field";

	public static boolean verify(HttpServletRequest request) {
	  		
        Map<String, String> map = HttpRequestHandler.getDataAsMap(request);   

        String challenge = map.get(RECAPTCHA_CHALLENGE_FIELD);
        String uresponse = map.get(RECAPTCHA_RESPONSE_FIELD);

        if (challenge == null || uresponse==null) {
        	return false;
        }
        
        String remoteAddr = request.getRemoteAddr();
        ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
        
        // this may send a nullpointerexception if you forget to set your private key
        reCaptcha.setPrivateKey(RECAPTCHA_PRIVATE_KEY.toString());
        ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(remoteAddr, challenge, uresponse);
        return reCaptchaResponse.isValid();
	}

  public static boolean recaptchaEnabled() {
    return _isEnabled;
  }


}
